package com.peng.herostory.cmdhanlder;

import com.peng.herostory.Broadcaster;
import com.peng.herostory.model.MoveState;
import com.peng.herostory.model.User;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public class UserMoveToCmdHandler implements ICmdHandler<GameMsgProtocol.UserMoveToCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserMoveToCmd cmd) {
        Integer userId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (null == userId) {
            return;
        }
        User user = UserManager.getUserById(userId);
        MoveState moveState = user.getMoveState();
        //记录用户的移动状态， 移动开始时间，起始位置，到达位置
        moveState.setFromPosX(cmd.getMoveFromPosX());
        moveState.setFromPosY(cmd.getMoveFromPosY());
        moveState.setToPosX(cmd.getMoveToPosX());
        moveState.setToPosY(cmd.getMoveToPosY());
        moveState.setStartTime(System.currentTimeMillis());

        GameMsgProtocol.UserMoveToResult moveToResult = GameMsgProtocol.UserMoveToResult.newBuilder()
                .setMoveUserId(userId)
                .setMoveToPosX(cmd.getMoveToPosX())
                .setMoveToPosY(cmd.getMoveToPosY())
                .setMoveFromPosX(cmd.getMoveFromPosX())
                .setMoveFromPosY(cmd.getMoveFromPosY())
                .setMoveStartTime(moveState.getStartTime())
                .build();
        Broadcaster.broadcast(moveToResult);
    }
}
